package study_1;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;

/**
 * 多线程简单应用实例：使用多线程下载文件
 * 每次下载操作都新建一个线程操作，可以大大提高程序运行效率，因为文件下载是阻塞式I/O操作
 */
public class Thread9 {
    public static void main(String[] args) {
        Thread downloaderThread = null;
        for (String url:args){
            //创建文件下载器线程
            Thread thread = new Thread(new FileDownloader(url));
            //启动文件下载器线程
            downloaderThread.start();
        }
    }
    //文件下载器
    static class FileDownloader implements Runnable{
        private final String fileURL;

        public FileDownloader(String fileURL){
            this.fileURL = fileURL;
        }
        @Override
        public void run() {
            System.out.println("Downloading from "+fileURL);
            String fileBaseName = fileURL.substring(fileURL.lastIndexOf('/') + 1);
            try{
                URL url = new URL(fileURL);
                String localFIleName = System.getProperty("java.io.tmpdir")
                        +"/viscent-"
                        +fileBaseName;
                System.out.println("Saving to:" + localFIleName);
                downloadFile(url, new FileOutputStream(localFIleName), 1024);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        //从指定的URL下载文件，并将其保存到指定的输出流中
        private void downloadFile(URL url, OutputStream outputStream, int bufSize){
            //下载文件逻辑
        }
    }
}
